<?php
/**
 * Created by PhpStorm.
 * User: Joshua Conero
 * Date: 2020/3/1
 * Time: 16:41
 * Email: conero@163.com
 */

namespace app\app\common\service;
use app\common\Aurora;
use think\facade\Cache;
use think\facade\Request;

require_once(ROOT_PATH.'extend/phpqrcode/phpqrcode.php');

class QrCode
{
    const ShareTypeName = 'CROS';
    /**
     *
     * @param {string} $text
     */
    static function png($text=null){
        $text = $text? $text: "It's a bad Code, Telling by Joshua Coerne!";
        \QRcode::png($text, false, QR_ECLEVEL_L, 8);
        exit;
    }

    /**
     * 获取用户登录分享链接
     * @return string
     */
    static function getUserShareLink(){
        $uid = getUserInfo('uid');
        $token = sha1($uid. '_'.  time(). mt_rand(100000, 999999));
        $sid = mt_rand(100000, 999999);
        $key = self::UserShareKey();

        $link = Request::domain() ."/wap/index/share?type=".self::ShareTypeName."&token=$token&sid=$sid";
        $data = ['token' => $token, 'uid' => $uid, 'sid' => $sid, 'type'=> self::ShareTypeName];
        Cache::set($key, $data);
        return $link;
    }

    /**
     * 用户登录共享二维码
     */
    static function UserShareCode(){
        QrCode::png(self::getUserShareLink());
    }

    /**
     * 共享检测并登录
     */
    static function UserShareCheck(){
        $uid = getUserInfo('uid');
        if(empty($uid)){
            $data = Cache::get(self::UserShareKey());
            debugOut([$data, self::UserShareKey()]);
            if(!empty($data)){
                $input = input();
                $token = $input['token'] ?? false;
                $uid = $input['uid'] ?? false;
                $sid = $input['sid'] ?? false;
                // 自动登录
                if($token === $data['token'] && $uid === $data['uid'] && $sid === $data['sid']){
                    Aurora::userLoginHandler($uid);
                    Cache::rm(self::UserShareKey());    //防止二次使用
                }
            }

        }
    }

    /**
     * 获取用户共享缓存键值
     * @return string
     */
    static function UserShareKey(){
        $uid = getUserInfo('uid');
        return sha1($uid . '_share');
    }
}